package com.zbh.uexam.service.impl;

import com.zbh.uexam.base.SystemCode;
import com.zbh.uexam.configuration.property.SystemConfig;
import com.zbh.uexam.domain.User;
import com.zbh.uexam.exception.CodeException;
import com.zbh.uexam.service.AuthenticationService;
import com.zbh.uexam.service.UserService;
import com.zbh.uexam.utility.DateTimeUtil;
import com.zbh.uexam.utility.RsaUtil;
import com.zbh.uexam.viewmodel.student.user.UserRegisterVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author zhoubh
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService {


    private final UserService userService;
    private final SystemConfig systemConfig;
    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    public AuthenticationServiceImpl(UserService userService, SystemConfig systemConfig, RedisTemplate<String, String> redisTemplate) {
        this.userService = userService;
        this.systemConfig = systemConfig;
        this.redisTemplate = redisTemplate;
    }


    /**
     * @param username username
     * @param password password
     * @return boolean
     */
    @Override
    public boolean authUser(String username, String password) {
        User user = userService.getUserByUserName(username);
        return authUser(user, username, password);
    }


    @Override
    public boolean authUser(User user, String username, String password) {
        if (user == null) {
            return false;
        }
        String encodePwd = user.getPassword();
        if (null == encodePwd || encodePwd.length() == 0) {
            return false;
        }
        String pwd = pwdDecode(encodePwd);
        return pwd.equals(password);
    }

    @Override
    public String pwdEncode(String password) {
        return RsaUtil.rsaEncode(systemConfig.getPwdKey().getPublicKey(), password);
    }

    @Override
    public String pwdDecode(String encodePwd) {
        return RsaUtil.rsaDecode(systemConfig.getPwdKey().getPrivateKey(), encodePwd);
    }

    @Override
    public void authCode(String email, String code) {
        if (!redisTemplate.hasKey(email)) {
            throw new CodeException(SystemCode.CodeError.getCode(), SystemCode.CodeError.getMessage());
        }
        String[] split = redisTemplate.opsForValue().get(email).split("/");
        String trueCode = split[0];
        Date date = DateTimeUtil.parse(split[1], DateTimeUtil.STANDER_FORMAT);
        if (!trueCode.equals(code)) {
            throw new CodeException(SystemCode.CodeError.getCode(), SystemCode.CodeError.getMessage());
        }
        Date now = new Date();
        if ((now.getTime() - date.getTime()) /1000 > 60) {
            throw new CodeException(SystemCode.CodeTimeOut.getCode(), SystemCode.CodeTimeOut.getMessage());
        }
    }
}
